/*
http 编程 路由转发 中间件
*/

// package main

// import (
// 	"fmt"
// 	"log"
// 	"net/http"
// 	"time"
// )

// func index(w http.ResponseWriter, r *http.Request) {
// 	fmt.Fprintf(w, "this is index")
// }

// func hello(w http.ResponseWriter, r *http.Request) {
// 	fmt.Fprintf(w, "hello world")
// }

// func timeHandler(next http.Handler) http.Handler {
// 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 		start := time.Now()
// 		log.Printf("started %s %s", r.Method, r.URL.Path)
// 		next.ServeHTTP(w, r)
// 		log.Printf("completed %s in %v", r.URL.Path, time.Since(start))
// 	})
// }

// func main() {
// 	// 创建路由转发器
// 	mux := http.NewServeMux()
// 	mux.Handle("/hello", timeHandler(http.HandlerFunc(hello)))
// 	mux.Handle("/", timeHandler(http.HandlerFunc(index)))
// 	http.ListenAndServe(":8080", mux)
// }

/*
web框架gin
*/

// package main

// import (
// 	"net/http"

// 	"github.com/gin-gonic/gin"
// )

// func main() {
// 	r := gin.Default()
// 	r.GET("/ping", func(c *gin.Context) {
// 		c.JSON(200, gin.H{
// 			"message": "pong",
// 		})
// 	})
// 	r.Run()
// }

/* 静态文件服务器 */
// func main() {
// 	router := gin.Default()
// 	// router.StaticFS("/static", http.Dir("C:\\Users\\15426\\Desktop\\learn_and_work\\project-go\\les18\\static"))
// 	router.StaticFS("/static", http.Dir("\\les18\\static")) // 注意路径 相对路径要准确，

// 	router.Run(":8080")
// }

/*
gin 携带参数 路由
*/

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "hello %s", name)
	})

	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := c.Request.Method + " => " + name + " is " + action
		c.String(http.StatusOK, message)
	})

	router.POST("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := c.Request.Method + " => " + name + " is " + action
		c.String(http.StatusOK, message)
	})

	router.Run(":8080")
}
